package com.atguigu.realtime.gmallpublisher.service;

import com.atguigu.realtime.gmallpublisher.mapper.OrderMapper;
import io.searchbox.client.JestClient;
import io.searchbox.core.Search;
import io.searchbox.core.SearchResult;
import io.searchbox.core.search.aggregation.TermsAggregation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author lzc
 * @Date 2020/12/8 9:34
 */
@Service
public class PublisherServiceImp implements PublisherService {

    @Autowired
    JestClient esClient;

    @Override
    public Long getTotalDau(String date) throws IOException {

        // 查询es返回结果
        Search search = new Search.Builder(DslUtil.getQueryAllJsonString()).addIndex("gmall_dau_info_" + date).addType("_doc").build();
        SearchResult searchResult = esClient.execute(search);
        Long total = searchResult.getTotal();
        return total == null ? 0 : total;
    }

    @Override
    public Map<String, Long> getHourDau(String date) throws IOException {
        Search search = new Search.Builder(DslUtil.getQueryHourDauJsonString()).addIndex("gmall_dau_info_" + date).addType("_doc").build();

        SearchResult searchResult = esClient.execute(search);

        TermsAggregation agg = searchResult.getAggregations().getTermsAggregation("group_by_loghour");

        Map<String, Long> result = new HashMap<>();
        if (agg != null) {
            List<TermsAggregation.Entry> buckets = agg.getBuckets();
            for (TermsAggregation.Entry bucket : buckets) {
                String hour = bucket.getKey();
                Long count = bucket.getCount();
                result.put(hour, count);
            }
        }
        return result;
    }

    @Autowired
    private OrderMapper order;

    @Override
    public BigDecimal getOrderAmount(String date) {
        return order.getOrderAmount(date);
    }

    @Override
    public Map<String, BigDecimal> getHourOrderAmount(String date) {
        List<Map<String, Object>> hourOrderAmountList = order.getHourOrderAmount(date);
        Map<String, BigDecimal> result = new HashMap<>();
        for (Map<String, Object> map : hourOrderAmountList) {
            String hour = map.get("create_hour").toString();
            BigDecimal totalAmount = (BigDecimal) map.get("total_amount");

            result.put(hour, totalAmount);
        }
        return result;
    }
}
